package com.lmonkey.servlet.my;

import com.lmonkey.servic.USERDao;
import com.lmonkey.shop.PHOTO;
import com.lmonkey.shop.USER;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;

@MultipartConfig
@WebServlet("/shangc/getphoto")
public class GetPhoto extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置字符集
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");

        //获取数据
        String username = request.getParameter("username");
        String file = request.getParameter("file");

        Part part = request.getPart("photo");
        String filename = part.getSubmittedFileName();
        if (!file.equals(filename)){
            //获取文件存储路径)
            String filepath = "D:\\java\\obj\\web\\shangc\\image\\headerphoto";
            System.out.println(filepath);
            //上传文件
            part.write(filepath+"\\"+filename);
            //将数据加入到数据库
            USERDao.updatePhoto(filename,username);
            if (!file.equals("tx.png")){
                //删除原来的头像
                String path = "D:\\java\\obj\\web\\shangc\\image\\headerphoto\\"+file+"";
                File cfile = new File(path);
                cfile.delete();
            }
        }

        //查找数据库
        PHOTO p =  USERDao.select(username);
        HttpSession session = request.getSession();
        session.setAttribute("hp",p);

        response.sendRedirect("mygrxxselect");
    }
}
